<template>
  <div class="i-table-no-border">
    <Button type="primary" icon="md-add" @click="handleOpenCreate">新建</Button>
    <Table highlight-row
      size="small"
      ref="table"
      :columns="columns"
      :data="list"
      :loading="loading"
      class="ivu-mt"
    >
      <template #status="{ row }">
        <Badge status="success" :text="row.status_str" v-if="row.status ==='1'"/>
        <Badge status="error" :text="row.status_str" v-else/>
      </template>
      <template #action="{row, index}">
        <a @click="handleUpdate(index)">编辑</a>
        <!-- <Divider type="vertical" />
        <a @click="handleDeleteItem(row)">删除</a> -->
      </template>
    </Table>
    <div class="ivu-mt ">
      <Page
        :total="total"
        :modelValue="current"
        show-total
        show-elevator
        :page-size="size"
        @on-change="handleChangePage"
        :page-size-opts="pageOpts"
        show-sizer
        @on-page-size-change="changePageSize"
      />
    </div>
    <Modal
      v-model="showCreate"
      :mask-closable="false"
      :title="title"
      :loading="creating"
      :draggable="true"
      @on-ok="handleCreate"
    >
      <Form
        ref="create"
        :model="createMenuData"
        :rules="createRules"
        :label-width="100"
      >
        <FormItem label="动作名称：" prop="name">
          <Input
            v-model="createMenuData.name"
            placeholder="请输入动作行为名称"
            :maxlength="30"
            clearable
          />
        </FormItem>
        <FormItem label="菜单名称：" prop="menu_id">
          <TreeSelect
            v-model="createMenuData.menu_id"
            :data="parentMenuList"
            v-width="200"
            :placeholder="placeholder"
            clearable
          />
        </FormItem>
        <FormItem label="动作路由：" prop="flag">
          <Input
            v-model="createMenuData.flag"
            placeholder="请输入路由"
            clearable
          />
        </FormItem>
        <FormItem label="排序：" prop="sort">
          <InputNumber v-model="createMenuData.sort" placeholder="排序" :min="0"/>
        </FormItem>
        <FormItem label="菜单状态：">
          <Switch v-model="createMenuData.status">
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </Switch>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  GetAction,
  DetailAction,
  CreateAction,
  UpdateAction,
  DeleteAction,
} from "@/api/menu.js";
export default {
  watch: {
    // createMenuData(value) {
    //   if (value.module_id !== "") {
    //     this.placeholder = "请选择";
    //   }
    // },
  },
  data() {
    return {
      columns: [
        {
          title: "唯一标识",
          key: "marking",
          minWidth: 160,
        },
        {
          title: "动作行为名称",
          key: "name",
          minWidth: 100,
        },
        {
          title: "菜单名称",
          key: "menu_name",
          minWidth: 100,
        },
        {
          title: "排序",
          key: "sort",
          width: 80,
        },
        {
          title: "状态",
          slot: "status",
          width: 100,
        },
        {
          title: "创建时间",
          key: "created_at_str",
          minWidth: 100,
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 100,
        },
      ],
      loading: false,
      list: [],
      placeholder: "请先选择模块",
      parentMenuList: [],
      pageOpts: [10, 20, 30, 50],
      current: 1,
      size: 10,
      total: 0,
      showCreate: false,
      createMenuData: {
        name: "",
        flag: "",
        module_id: 1,
        menu_id: "",
        status: true,
        sort: null,
      },
      createRules: {
        name: [
          {
            required: true,
            message: "请输入动作行为名称",
            trigger: "blur",
          },
        ],
        sort: [
          {
            message: "排序必须是正数字",
            pattern: /^[+]{0,1}(\d+)$/,
            trigger: "blur",
          },
        ],
        menu_id: [{ required: true, message: "请选择菜单", trigger: "blur" }],
        module_id: [{ required: true, message: "请选择模块", trigger: "blur" }],
        flag: [{ required: true, message: "请输入路由", trigger: "blur" }],
        status: [
          {
            required: true,
            message: "请输入动作行为状态",
            trigger: "blur",
          },
        ],
      },
      creating: true,
      updateIndex: -1,
      editing: true,
      title: "新增",
    };
  },
  methods: {
    filterArr(arr, id) {
      // console.log(arr,'arr')
      arr.forEach((ee) => {
        if (ee.children && !(ee.children instanceof Array)) {
          ee.children = [...ee.children[id]];
          this.filterArr(ee.children);
        } else {
          return false;
        }
      });
      return arr;
    },
    getData() {
      this.loading = true;
      GetAction({
        pageSize: this.size,
        page: this.current,
      })
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取父级菜单
    getParentMenuList(id) {
      DetailAction({ id: id }).then((res) => {
        this.parentMenuList = res.condition.menu;
      });
    },
    handleSelectModule(value) {
      // 选中动作行为
      if (!value) return false;
      this.getParentMenuList(value);
    },
    // 点击切换分页
    handleChangePage(currentPage) {
      this.current = currentPage;
      this.getData();
    },
    changePageSize(e) {
      this.size = e;
      this.getData();
    },
    handleClickItem(name) {},
    // 点击新增
    handleOpenCreate() {
      this.updateIndex = -1;
      this.showCreate = true;
      this.title = "新增";
      this.getParentMenuList(1);
      // this.$nextTick(() => {
      //   this.$refs["create"].resetFields();
      //   this.$nextTick(() => {
      //     this.placeholder = "请先选择模块";
      //   });
      // });
    },
    // 新增数据
    handleCreate() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.createMenuData));
          sendData.status = sendData.status === true ? "1" : "0";
          if (this.updateIndex < 0) {
            // 新建
            CreateAction(sendData).then((res) => {
              // 创建动作行为成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success("创建动作行为成功");
            });
          } else {
            // 修改
            UpdateAction(sendData).then((res) => {
              // 修改动作行为成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success("修改成功");
            });
          }
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        } else {
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        }
      });
    },
    // 删除动作行为
    handleDeleteItem(row) {
      this.$Modal.confirm({
        title: "警告",
        content: "是否确认删除该动作行为",
        onOk: () => {
          DeleteAction({
            id: row.id,
          }).then((res) => {
            if (this.list.length === 1) this.current--;
            this.getData();
            this.$Message.success("删除成功");
          });
        },
      });
    },
    // 编辑数据
    handleUpdate(index) {
      this.showCreate = true;
      this.title = "编辑";
      this.$nextTick(() => {
        this.$refs["create"].resetFields();
        this.updateIndex = index;
        const item = this.list[index];
        this.getParentMenuList(item.id);
        //  this.getParentMenuList(1);
        for (let key in this.createMenuData) {
          if(key=='sort'){
            this.createMenuData[key] = +item[key];
          }else{
            this.createMenuData[key] = item[key];
          }
          
        }
        this.createMenuData.status = this.createMenuData.status === "1";
        this.createMenuData.id = item.id;
        this.createMenuData.module_id =1;

      });
    },
  },
};
</script>
<style lang="less" scoped>
  /deep/.ivu-badge-status-text{
    font-size: 12px;
  }
</style>